#ifndef DATA_CHART_H
#define DATA_CHART_H

#include <QWidget>
#include <QtCharts>
#include <QToolTip>
#include <cmath> // 用于计算距离
namespace Ui {
class Data_chart;
}

class Data_chart : public QWidget
{
    Q_OBJECT

public:
    explicit Data_chart(QWidget *parent = nullptr);
    ~Data_chart();
    void data_chart(void);
private slots:
    // serial port
    void on_start_clicked();
    void on_clear_line_clicked();
    void on_new_line_clicked();

private:
    Ui::Data_chart *ui;

    void data_handle(void);
};


extern Data_chart *data_chart;

// 自定义图表视图，用于处理鼠标事件
class CustomChartView : public QChartView {
    Q_OBJECT
public:
    explicit CustomChartView(QChart *chart, QWidget *parent = nullptr)
        : QChartView(chart, parent) {
        setMouseTracking(true); // 开启鼠标跟踪（无需按下鼠标即可触发move事件）
        setToolTipDuration(0); // Tooltip 持续显示，直到鼠标移开
    }

protected:
    void mouseMoveEvent(QMouseEvent *event) override {
        // 1. 转换鼠标坐标为图表数值坐标
        QPointF mousePos = event->pos();
        QPointF chartPos = mapToScene(mousePos.toPoint());
        QPointF valuePos = chart()->mapToValue(chartPos);

        // 2. 遍历所有系列（处理多条线）
        const qreal threshold = 10.0; // 检测阈值（可调整）
        bool isNearAnyLine = false;
        QString tooltip;
        QLineSeries *nearestSeries = nullptr;
        QPointF nearestPoint;
        qreal minDistance = threshold; // 记录最近距离

        foreach (QAbstractSeries *series, chart()->series()) {
            // 过滤非线系列（只处理QLineSeries）
            QLineSeries *lineSeries = qobject_cast<QLineSeries*>(series);
            if (!lineSeries) continue;

            // 检查当前系列的所有线段
            QList<QPointF> points = lineSeries->points(); // 获取所有数据点
            for (int i = 0; i < points.size() - 1; ++i) {
                QPointF p1 = points[i];
                QPointF p2 = points[i+1];

                // 转换数据点为屏幕坐标（用于计算距离）
                QPointF s1 = chart()->mapToPosition(p1);
                QPointF s2 = chart()->mapToPosition(p2);
                QPointF mouseScreenPos = chart()->mapToPosition(valuePos);

                // 计算鼠标到线段的距离
                qreal distance = distanceToLine(mouseScreenPos, s1, s2);
                if (distance < minDistance) {
                    // 更新最近的系列和点
                    minDistance = distance;
                    isNearAnyLine = true;
                    nearestSeries = lineSeries;
                    // 取线段上最近的点（简化为端点，也可插值）
                    nearestPoint = (QLineF(mouseScreenPos, s1).length() < QLineF(mouseScreenPos, s2).length()) ? p1 : p2;
                }
            }
        }

        // 3. 显示Tooltip（包含系列名称和坐标）
        if (isNearAnyLine && nearestSeries) {
            tooltip = QString("%1\nX: %2\nY: %3")
            .arg(nearestSeries->name()) // 显示线的名称（系列名称）
                .arg(nearestPoint.x(), 0, 'f', 2)
                .arg(nearestPoint.y(), 0, 'f', 2);
            // 关键：第三个参数传this，确保Tooltip在当前窗口显示
            QToolTip::showText(event->globalPosition().toPoint(), tooltip, this);
        } else {
            QToolTip::hideText();
        }

        QChartView::mouseMoveEvent(event);
    }

private:
    // 计算点到线段的垂直距离
    qreal distanceToLine(const QPointF &point, const QPointF &lineP1, const QPointF &lineP2) {
        qreal dx = lineP2.x() - lineP1.x();
        qreal dy = lineP2.y() - lineP1.y();
        qreal a = point.x() - lineP1.x();
        qreal b = point.y() - lineP1.y();
        qreal len2 = dx*dx + dy*dy;

        if (len2 == 0) return sqrt(a*a + b*b);
        qreal t = qMax(0.0, qMin(1.0, (a*dx + b*dy) / len2));
        qreal projX = lineP1.x() + t*dx;
        qreal projY = lineP1.y() + t*dy;
        return sqrt((point.x() - projX)*(point.x() - projX) + (point.y() - projY)*(point.y() - projY));
    }
};

#endif // DATA_CHART_H
